package path;

import java.util.ArrayList;
import java.util.Iterator;

import processing.core.PApplet;

public class LoopPath extends Path{
	private long stopTime;
	private long trailLength;
	private long currentFrame;
	private long startPlayTime;
	
	public LoopPath(PApplet pa, long trailLength) {
		super(pa);
		this.trailLength = trailLength;
	}
	
	public void addFrame(KeyFrame kf){
		int size = keyFrames.size();
		super.addFrame(kf);
		for(int i = size; i < keyFrames.size(); i++){
			KeyFrame k = getKeyFrameByIndex(i);
			//kf.setTime(kf.getTime() - startTime);
			stopTime = getLastKeyFrame().getTime();
		}
	}
	
	public void addFrames(ArrayList l){
		Iterator i = l.iterator();
		while(i.hasNext()){
			addFrame((KeyFrame)i.next());
		}
	}

	public void update(){
		currentFrame = (System.currentTimeMillis() - startPlayTime) % stopTime;
	}
	
	public void start(){
		startPlayTime = System.currentTimeMillis();
	}
	
	public void draw(PApplet pa){
		update();
		Iterator i = keyFrames.iterator();
		while(i.hasNext())
			setVisibility(currentFrame, (KeyFrame)i.next(), trailLength);
		
		Iterator d = drawers.iterator();
		while(d.hasNext())
			((PathDrawer)d.next()).drawPath(this, pa);
	}
	
	private void setVisibility(long currentFrame, KeyFrame kf, long trailLength){
		long diff = currentFrame - kf.getTime();
		if(diff < 0)
			diff = diff + (stopTime);
		
		if(diff > trailLength || diff < 0){
			kf.setVisibility(0f);
			return;
		}
		
		kf.setVisibility(1 - (float)diff / (float)trailLength);
	}
}
